package com.mzj.saas.mservice.smartlock.service.youdian;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.smartlock.base.BaseLock;
import com.mzj.saas.mservice.smartlock.vo.DevMacStateVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockFingerprintVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SmartLockYdService implements BaseLock {

    @Value("${youDian.token}")
    private String youDianToken;
    @Value("${youDian.deviceModel}")
    private String youDianDeviceModel;
    @Value("${youDian.url}")
    private String youDianUrl;

    /**
     * 授权密码和授权临时密码
     *
     * @param vo
     * @param smartLockPwd
     * @return
     */
    @Override
    public ResultBean<String> authorizationPwd(SmartLockVO vo, SmartLockPwd smartLockPwd) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        //判断授权密码是否已经过期，如果过期直接返回成功
        Date endTime1 = smartLockPwd.getEndTime();
        if (endTime1 != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime1.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }
        String startTime = DateUtil.formatDateTime(smartLockPwd.getStartTime());
        String endTime = DateUtil.formatDateTime(smartLockPwd.getEndTime());
        hashMap.put("imei", vo.getSn());
        hashMap.put("password", vo.getPassword());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_NUMBER);
        hashMap.put("permanentFlag", SmartLock.PERMANENT_FLAG_NO);
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", startTime);
        hashMap.put("endTime", endTime);
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }


    /**
     * 删除密码授权
     *
     * @param vo
     * @param lockAuthId
     * @return
     */
    @Override
    public ResultBean<String> deletePwd(SmartLockVO vo, Long lockAuthId) {
        //判断授权指纹是否已经过期，如果过期直接返回成功
        Date endTime = DateUtil.parse(vo.getEndTime());
        if (endTime != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }
        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + vo.getReturnPwdId())
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }


    /**
     * 授权指纹开锁
     *
     * @param vo
     * @return
     */
    @Override
    public ResultBean<String> fingerprintUnlocking(SmartLockFingerprintVO vo) {
        return null;
    }

    /**
     * 删除指纹开锁
     *
     * @param vo
     * @return
     */
    @Override
    public ResultBean<String> deleteFingerprintUnlocking(SmartLockVO vo) {
        return null;
    }

    /**
     * 授权门卡开锁
     *
     * @return
     */
    @Override
    public boolean doorCardUnlocking() {
        return false;
    }

    /**
     * 授权身份证/CUP卡开锁
     *
     * @param vo
     * @param smartLockCard
     * @return
     */
    @Override
    public ResultBean<String> identityCardUnlocking(SmartLockVO vo, SmartLockCard smartLockCard) {
        //判断授权身份证是否已经过期，如果过期直接返回成功
        Date endTime1 = smartLockCard.getEndTime();
        if (endTime1 != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime1.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", vo.getSn());
        hashMap.put("password", smartLockCard.getCardNumber());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_CARD);
        hashMap.put("permanentFlag", SmartLock.PERMANENT_FLAG_NO);
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", smartLockCard.getStartTime());
        hashMap.put("endTime", smartLockCard.getEndTime());
        hashMap.put("icCardModel", smartLockCard.getType());
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }

    /**
     * 删除身份证/CUP卡开锁
     *
     * @param vo
     * @return
     */
    @Override
    public ResultBean<String> deleteIdentityCardUnlocking(SmartLockVO vo) {
        //判断授权指纹是否已经过期，如果过期直接返回成功
        Date endTime = DateUtil.parse(vo.getEndTime());
        if (endTime != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }
        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + vo.getReturnCardId())
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }

    /**
     * 授权蓝牙开锁
     *
     * @param vo
     * @param smartLockBle
     * @return
     */
    @Override
    public ResultBean<String> bluetoothUnlocking(SmartLockVO vo, SmartLockBle smartLockBle) {
        return null;
    }

    /**
     * 获取蓝牙密钥
     *
     * @param lockAuthId
     * @return
     */
    @Override
    public ResultBean<String> getBluetoothUnlocking(Long lockAuthId) {
        return null;
    }

    /**
     * 删除蓝牙开锁权限
     *
     * @param vo
     * @return
     */
    @Override
    public ResultBean<String> deleteBluetoothUnlocking(SmartLockVO vo) {
        return null;
    }

    /**
     * 删除智能锁所有授权及解绑
     *
     * @param sn
     * @param lockId
     * @return
     */
    @Override
    public ResultBean<String> deleteAll(String sn, Long lockId) {
        String result = HttpRequest.delete(youDianUrl + "commercial/device?imei=" + sn)
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }

    /**
     * 注册智能锁
     *
     * @param sn 智能锁SN号
     * @return
     */
    public String insertSmartLock(String sn) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", sn);
        hashMap.put("deviceModel", youDianDeviceModel);
        hashMap.put("buttPlatformType", SmartLock.BUTT_PLATFORM_TYPE_TELECOM);
        String result = HttpRequest.post(youDianUrl + "commercial/device")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 新增授权人脸信息
     *
     * @param smartLockFace 人脸信息
     * @return
     */
    public ResultBean<String> addFaceImage(SmartLockFace smartLockFace) {
        //判断授权人脸是否已经过期，如果过期直接返回成功
        Date endTime = smartLockFace.getEndTime();
        if (endTime != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLockFace.getSn());
        hashMap.put("faceImage", smartLockFace.getFaceImage());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_FACE);
        hashMap.put("permanentFlag", smartLockFace.getAuthType());
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", smartLockFace.getStartTime());
        hashMap.put("endTime", smartLockFace.getEndTime());
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        Long id  = (Long) JSONObject.parseObject(result).getJSONObject("data").get("id");
        return ResultBean.successfulResult(id.toString());
    }

    /**
     * 判断是否请求成功
     *
     * @param result
     * @return
     */
    private ResultBean<String> getStringResultBean(String result) {
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(result);
        Integer code = (Integer) jsonObject.get("code");
        if (code != 0) {
            ResultBean<String> objectResultBean = new ResultBean<>();
            objectResultBean.setMsg((String) jsonObject.get("message"));
            objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            return objectResultBean;
        }
        return null;
    }

    /**
     * 新增授权人脸信息
     *
     * @param newSmartlockface 人脸信息
     * @return
     */
    public ResultBean<String> updateFaceImage(SmartLockFace newSmartlockface) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("id", newSmartlockface.getReturnFaceId());
        hashMap.put("operationType", 2);
        hashMap.put("startTime", newSmartlockface.getStartTime());
        hashMap.put("endTime", newSmartlockface.getEndTime());
        String result = HttpRequest.put(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(result);
    }


    /**
     * 删除授权人脸信息
     *
     * @param smartLockFace 授权人脸信息
     * @return
     */
    public ResultBean<String> deleteFaceImage(SmartLockFace smartLockFace) {
        //判断授权人脸是否已经过期，如果过期直接返回成功
        Date endTime = smartLockFace.getEndTime();
        if (endTime != null) {
            DateTime date = DateUtil.date();
            //结束时间比当前时间早
            boolean before = endTime.before(date);
            if (before) {
                return ResultBean.successfulResult("成功");
            }
        }

        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + smartLockFace.getReturnFaceId())
                .header("token", youDianToken)
                .timeout(20000)
                .execute().body();
        ResultBean<String> objectResultBean = getStringResultBean(result);
        if (objectResultBean != null) return objectResultBean;
        return ResultBean.successfulResult(null);
    }

    /**
     * 查询设备信息
     * @param id
     * @return
     */
    public ResultBean<DevMacStateVO> deviceList(String id) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", id);
        String result = HttpRequest.get(youDianUrl + "commercial/device")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(result);
        Integer code = (Integer) jsonObject.get("code");
        if (code != 0) {
            return null;
        }
        //智能锁状态，没有绑定，默认离线，绑定了就在线了
        //Integer deviceStatus = (Integer) jsonObject.getJSONObject("data").get("deviceStatus");
        Integer batteryLevel = (Integer) jsonObject.getJSONObject("data").get("batteryLevel");
        DevMacStateVO devMacStateVO = new DevMacStateVO();
        devMacStateVO.setState(1);
        devMacStateVO.setBattery(batteryLevel);
        return ResultBean.successfulResult(devMacStateVO);
    }
}
